package com.example.securityconfiggen.controller;

import com.example.securityconfiggen.model.YamlRequest;
import com.example.securityconfiggen.service.YamlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import javax.validation.Valid;
import java.util.Map;

@Controller
public class YamlController {

    @Autowired
    private YamlService yamlService;

    @GetMapping("/yaml")
    public String yamlPage(Model model) {
        model.addAttribute("yamlRequest", new YamlRequest());
        return "yaml";
    }

    @PostMapping("/yaml/process")
    public String processYaml(@Valid @ModelAttribute("yamlRequest") YamlRequest request,
                             BindingResult bindingResult,
                             Model model) {
        if (bindingResult.hasErrors()) {
            return "yaml";
        }

        try {
            // 处理YAML内容
            Map<String, String> results = yamlService.processYaml(request.getProjectName(), request.getYamlContent());

            // 将结果放入模型中
            model.addAttribute("md5Result", results.get("md5"));
            model.addAttribute("base64Result", results.get("base64"));
            model.addAttribute("keyvaultCommands", results.get("keyvaultCommands"));
            model.addAttribute("hasResults", true);
            
            // 保持用户输入的内容
            model.addAttribute("yamlRequest", request);
            
            return "yaml";
        } catch (Exception e) {
            // 添加错误信息
            bindingResult.rejectValue("yamlContent", "error.yamlContent", "处理YAML内容时出错: " + e.getMessage());
            return "yaml";
        }
    }
} 